package com.molichuxing.gateway.utils;

import com.alibaba.fastjson.JSONObject;
import com.moli.iov.util.JwtTokenUtil;
import com.molichuxing.framework.contants.RedisKeyConst;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.Md5Util;
import com.molichuxing.framework.utils.RedisUtil;
import com.molichuxing.framework.utils.StringUtil;
import com.molichuxing.gateway.utils.entity.UserEntity;
import com.molichuxing.services.infrastructure.dto.response.response.AccountDto;
import com.molichuxing.services.property.SystemTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * 用户token工具类
 * 
 * @author zoumingyu
 * @date 2019年8月19日
 *
 */
@Component
public class TokenUtil {
	private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

	// 环境
	@Value("${profiles.active}")
	private String active;

	@Value("${token.expiration}")
	private Integer expiration;

	@Value("${token.jwt.tokenHead}")
	private String tokenHead;

	@Resource
	private SSOTokenUtil ssoTokenUtil;

	@Resource
	private RedisUtil redisUtil;

	/**
	 * 设置用户token
	 * 
	 * @param user
	 *            用户信息
	 */
	public String setUserToken(UserEntity user) {
		// 计算超时时间
		// 生成token(TOKEN_KEY+MD5_16bit(环境).MD5_16bit((用户账号+用户名).MD5_16bit((当前时间+随机数))
		String date = DateUtil.formatTime(LocalDateTime.now());

		String token = RedisKeyConst.TOKEN_OP_KEY + Md5Util.md5Hex(active) +"."+  Md5Util.md5Hex(user.getAccount());
		redisUtil.setex(token, JSONObject.toJSONString(user), expiration.intValue());
		return token;
	}

	/**
	 * 获取用户信息
	 * 
	 * @param ssoToken
	 *            token
	 * @return
	 */
	public UserEntity getUser(String ssoToken) {
		String token = ssoTokenToRedisKeyToken(ssoToken);

		String user = redisUtil.get(token);
		return user == null ? null : JSONObject.parseObject(user, UserEntity.class);
	}

	public UserEntity getUser() {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		return getUser(request.getHeader("token"));
	}

	public void deleteUserByAccount(String account) {
		String tokenKey = RedisKeyConst.TOKEN_OP_KEY + Md5Util.md5Hex(active) +"."+  Md5Util.md5Hex(account);
		redisUtil.del(tokenKey);
	}

	public void deleteUserByAccount(AccountDto account) {
		String tokenKey = null;
		if (account.getSystemType().getValue() == SystemTypeEnum.OP.getValue()) {
			tokenKey = RedisKeyConst.TOKEN_OP_KEY + Md5Util.md5Hex(active) +"."+  Md5Util.md5Hex(account.getAccount());
		} else {
			tokenKey = RedisKeyConst.TOKEN_DEALER_KEY + Md5Util.md5Hex(active) +"."+  Md5Util.md5Hex(account.getAccount());
		}

		if (!StringUtil.isEmpty(tokenKey)) {
			redisUtil.del(tokenKey);
		}
	}

	public void deleteCurrentUser() {
		UserEntity currentUser = getUser();
		if (currentUser != null && currentUser.getAccountId() > 0) {
			deleteUserByAccount(currentUser.getAccount());
		}
	}

	public void expire(String ssoToken) {
		redisUtil.expire(ssoTokenToRedisKeyToken(ssoToken), expiration.intValue());
	}

	public String ssoTokenToRedisKeyToken(String ssoToken) {
		String account = ssoTokenUtil.getAccountFromSsoToken(ssoToken);
		String token = RedisKeyConst.TOKEN_OP_KEY + Md5Util.md5Hex(active) +"."+  Md5Util.md5Hex(account);
		return token;
	}
}
